package com.zzj.web.restfulservice.impl;

import com.zzj.bill.domain.BillSellDetail;
import com.zzj.bill.domain.BillShop;
import com.zzj.bill.domain.BillUserShop;
import com.zzj.bill.service.*;
import com.zzj.common.core.domain.entity.SysUser;
import com.zzj.common.core.domain.model.LoginUser;
import com.zzj.common.utils.DateUtils;
import com.zzj.common.utils.SecurityUtils;
import com.zzj.common.utils.StringUtils;
import com.zzj.system.service.ISysDeptService;
import com.zzj.system.service.ISysUserService;
import com.zzj.web.controller.exception.BillRestfulException;
import com.zzj.web.restfulservice.SellDetailRestfulService;
import com.zzj.web.utils.BillUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.zzj.common.utils.PageUtils.startPage;

/**
 * 业务逻辑类
 *
 * @Author zengZhiJun
 * @create 2022/1/24 14:12
 */
@Service("SellDetailRestfulService")
public class SellDetailRestfulServiceImpl implements SellDetailRestfulService {

    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private IBillSellDetailService sellDetailService;
    @Autowired
    private GeneratorService generatorService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private IUserShopService userShopService;
    @Autowired
    private ISysUserService userService;

    /**
     * 新增
     *
     * @param sellDetail
     * @return
     */
    @Override
    public int insert(BillSellDetail sellDetail) {
        //获取登入用户的信息,并校验
        Pair<LoginUser, BillShop> pair = getLoginUserInfo();
        // 填充对象属性
        BillSellDetail db = fillAttribute(pair, sellDetail);
        //入库
        return sellDetailService.insertBillSellDetail(db);
    }

    /**
     * 分页查询
     *
     * @param sellDetail
     * @return
     */
    @Override
    public List<BillSellDetail> selectByPage(BillSellDetail sellDetail) {
        Pair<LoginUser, List<BillShop>> pair = BillUtils.getLoginUserInfo();
        List<BillShop> billShops = pair.getRight();
        if (CollectionUtils.isEmpty(billShops)) {
            throw new BillRestfulException("当前登入用户没有关联任务店铺");
        }
        startPage();
        //默认查询当日的数据
        if (sellDetail.getSellTime() == null) {
            sellDetail.setSellTime(DateUtils.getNowDate());
        }
        List<BillSellDetail> list = sellDetailService.selectDetailByShopIds(sellDetail, billShops.stream().map(BillShop::getId).collect(Collectors.toList()));
        return list;
    }

    /**
     * 根据店铺查询店铺的员工
     *
     * @return
     */
    @Override
    public List<SysUser> getUserInfo() {
        Pair<LoginUser, List<BillShop>> pair = BillUtils.getLoginUserInfo();
        //当前登入用户关联的店铺id的集合
        List<Integer> shopIds = pair.getRight().stream().map(BillShop::getId).collect(Collectors.toList());
        //查user
        List<SysUser> userList = userService.findUserByShopIds(shopIds);
        return userList;
    }

    @Override
    public List<BillSellDetail> setValue(List<BillSellDetail> list) {
        Set<Integer> userIds = list.stream().map(BillSellDetail::getSellBy).collect(Collectors.toSet());
        List<SysUser> users = userService.selectUserByIds(userIds);
        Map<Long, SysUser> userMap = users.stream().collect(Collectors.toMap(SysUser::getUserId, sysUser -> sysUser));
        for (BillSellDetail billSellDetail : list) {
            SysUser sysUser = userMap.get(billSellDetail.getSellBy().longValue());
            if(null != sysUser){
                billSellDetail.setSellByName(sysUser.getUserName());
            }
        }
        return list;
    }

    private BillSellDetail fillAttribute(Pair<LoginUser, BillShop> pair, BillSellDetail sellDetail) {
        //订单号
        Long num = generatorService.generate(pair.getRight().getShopName(), 0, true);
        String numStr = StringUtils.leftPad(num.toString(), 4, "0");
        StringBuilder orderNo = new StringBuilder();
        for (String s : Arrays.asList(LocalDate.now().toString().split("-"))) {
            orderNo = orderNo.append(s);
        }
        sellDetail.setOrderNo(String.format("%s-%s", orderNo.toString(), numStr));
        int i = Optional.ofNullable(sellDetail.getByoutOrnot()).orElse(0);
        sellDetail.setByoutOrnot(i);
        sellDetail.setIntoSystem(0);
        //设置买断款状态  买断款1 未买断0 对应
        if (sellDetail.getByoutOrnot() == 1) {
            //买断款状态0：未出库 1：已出库
            sellDetail.setByoutStatus(0);
        }
        sellDetail.setSellTime(DateUtils.getNowDate());
        sellDetail.setShopId(pair.getRight().getId());
        return sellDetail;
    }

    private Pair<LoginUser, BillShop> getLoginUserInfo() {
        //获取登入账号的deptId 映射成店铺的id，只有终端才能操作新增业务
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //查询用户关联的店铺
        List<BillUserShop> billUserShops = userShopService.selectUserShopByUserId(loginUser.getUserId().intValue());
        if (billUserShops.size() > 2) {
            throw new BillRestfulException("当前登入用户关联多个店铺，无法操作新增销售业务");
        }
        if (CollectionUtils.isEmpty(billUserShops)) {
            throw new BillRestfulException("当前登入用户未关联店铺，无法操作新增销售业务");
        }
        //查询店铺
        BillShop billShop = shopService.selectShopById(billUserShops.stream().map(BillUserShop::getShopId).collect(Collectors.toList()).get(0));
        if (null == billShop) {
            throw new BillRestfulException("当前登入用户未关联店铺，无法操作新增销售业务");
        }

       /* Long deptId = loginUser.getDeptId();
        SysDept sysDept = iSysDeptService.selectDeptById(deptId);
        if (null == sysDept) {
            throw new BillRestfulException("未能查到对应 dept 信息");
        }
        if (sysDept.getAncestors().split(",").length < 3) {
            throw new BillRestfulException("当前登入用户没用权限操作新增业务");
        }*/
        return Pair.of(loginUser, billShop);
    }
}
